#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>   


#define SERVER "server_sock"
#define READER_SERVER "READER"

int main(int argc, char *argv[])
{
    int sockfd, sendfd = 0;
    struct sockaddr_un addr, demoaddr;

    unlink(SERVER);
    bzero ( &addr, sizeof(addr) );
    bzero ( &demoaddr, sizeof(demoaddr) );
    addr.sun_family = AF_LOCAL;
    strcpy(addr.sun_path, SERVER);
    socklen_t len = sizeof(addr);

    sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket error");
        exit(-1);
    }

    if (bind(sockfd, (struct sockaddr *)&addr, len) < 0)
    {
        perror("bind error");
        close(sockfd);
        exit(-1);
    }
    printf("Bind is ok\n");


    demoaddr.sun_family = AF_LOCAL;
    strcpy(demoaddr.sun_path, READER_SERVER);
    socklen_t recvlen = sizeof(demoaddr);
    sendfd = socket(AF_LOCAL, SOCK_DGRAM, 0);
    if (sendfd < 0)
    {
        perror("socket error");
        exit(-1);
    }

    fd_set fdR;
    struct timeval timeout, tmp;
    timeout.tv_sec = 3;
    timeout.tv_usec = 0;
    tmp = timeout;

    while (1)
    {
        FD_ZERO(&fdR);
        FD_SET(sockfd, &fdR);
        switch (select(sockfd + 1, &fdR, NULL, NULL, &tmp))
        {
        case -1:
            printf("error\n");
            break;
        case 0:
            printf("timeout\n");
            tmp = timeout;
            break;
        default:
            if (FD_ISSET(sockfd, &fdR))
            {
                char recv_buf[20] = "";
                recvfrom(sockfd, recv_buf, 50, 0, (struct sockaddr *)NULL, &len);
                printf("%s\n", recv_buf);
                sprintf(recv_buf, "OK");
                int byte = sendto(sendfd, recv_buf, strlen(recv_buf), 0, (struct sockaddr *)&demoaddr, sizeof(demoaddr));
                printf("byte %d %s %s %s\n", byte, recv_buf, demoaddr.sun_path, strerror(errno));
            }
        }
    }
    return 0;
}